package com.cljh.controller;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.cljh.bean.Distinct;
import com.cljh.config.AuthAccess;
import com.cljh.controller.page.*;
import com.cljh.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.List;

/**
 * <p>
 *  商品模块
 * </p>
 *
 * @author cljh
 * @since 2022-11-27
 */
@RestController
@RequestMapping("/products")
public class ProductController {

    @Autowired
    ProductService productService;

    /**
     * 分页查询
     * @param pn 当前页面
     * @param size 每页显示数量
     * @param product 商品类
     * @return Result
     */
    @AuthAccess
    @PostMapping("/{pn}/{size}")
    public Result selectProduct(@PathVariable(value = "pn") Integer pn, @PathVariable(value = "size")Integer size, @RequestBody ProductPageBean product){
        PageBean<ProductPageBean> productPageBean =  productService.selectAllByCondition(pn, size, product);

        Integer code=productPageBean !=null ? Code.GET_OK:Code.GET_ERR;
        String msg=productPageBean!=null ? "查询到信息":"未查询到信息";
        return new Result(code,productPageBean,msg);
    }

    /**
     *添加
     * @param product 商品类
     * @return
     */
    @PostMapping
    public Result save(@RequestBody ProductPageBean product){

        boolean save = productService.save(product);
        flushRedis(Code.FILES_KEY);
        flushRedis(Code.SELECT_PRODUCT);
        Integer code=save ? Code.SAVE_OK:Code.SAVE_ERR;
        String msg=save ? "添加成功":"添加失败";
        return new Result(code,save,msg);
    }

    /**
     * id删除
     * @param id
     * @return Result
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        boolean delete = productService.delete(id);
        flushRedis(Code.FILES_KEY);
        flushRedis(Code.SELECT_PRODUCT);
        Integer code=delete ? Code.DELETE_OK:Code.DELETE_ERR;
        String msg=delete ? "删除一个成功":"删除一个失败";
        return new Result(code,delete,msg);
    }

    /**
     * 更新
     * @param product 商品类
     * @return Result
     */
    @PutMapping
    public Result update(@RequestBody ProductPageBean product){
        boolean update = productService.update(product);
        flushRedis(Code.FILES_KEY);
        flushRedis(Code.SELECT_PRODUCT);
        Integer code=update ? Code.UPDATE_OK:Code.UPDATE_ERR;
        String msg=update ? "修改成功":"修改失败";
        return new Result(code,update,msg);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping("/deleteIds")
    public Result deleteByIds(@RequestBody List<Integer> ids){
        boolean b = productService.deleteByIds(ids);
        flushRedis(Code.FILES_KEY);
        flushRedis(Code.SELECT_PRODUCT);
        Integer code=b ? Code.DELETE_OK:Code.DELETE_ERR;
        String msg=b ? "删除成功":"删除失败";
        return new Result(code,b,msg);
    }

    /**
     * id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        ProductPageBean product = productService.selectById(id);
        Integer code=product !=null ? Code.GET_OK:Code.GET_ERR;
        String msg=product!=null ? "查询到信息":"未查询到信息";
        return new Result(code,product,msg);
    }

    /**
     * 导出excel表格
     * @param response
     * @throws Exception
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response)throws Exception{
        //从数据库查询出所有数据
        List<ProductPageBean> list=productService.ProductList();
        //通过工具创建writer 写出到磁盘路径
//        ExcelWriter writer= ExcelUtil.getWriter(filesUploadPath+"/用户信息.xlsx");
        //内存操作，写出到浏览器
        ExcelWriter writer=ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id" ,"id");
        writer.addHeaderAlias("productName" ,"商品名称");
        writer.addHeaderAlias("productSum" ,"商品总量");
        writer.addHeaderAlias("price" ,"价格");
        writer.addHeaderAlias("cost" ,"进价");
        writer.addHeaderAlias("types" ,"款式");
        writer.addHeaderAlias("productDesign" ,"商品厂家");
        writer.addHeaderAlias("productColor" ,"商品颜色");
        writer.addHeaderAlias("productDetail" ,"商品详情信息");
        writer.addHeaderAlias("productMaterials" ,"商品材质");
        writer.addHeaderAlias("productSize" ,"商品尺码");
        writer.addHeaderAlias("season" ,"季度");
        writer.addHeaderAlias("img" ,"照片一");
        writer.addHeaderAlias("img1" ,"照片二");
        writer.addHeaderAlias("img2" ,"照片三");
        writer.addHeaderAlias("createTime" ,"创建时间");
        writer.addHeaderAlias("showId" ,"商品id");
        //一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list,true);
        //设置浏览器响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName= URLEncoder.encode("商品信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
        ServletOutputStream out =response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();

    }




    /**
     * 导入excel
     * @param file
     */
    @PostMapping("/import")
    public void importExcel(MultipartFile file) throws IOException, ParseException {
        System.out.println(file);
        //1.第一种 头必须和实体(英文)一样
        //文件处理成io流
        InputStream in = file.getInputStream();
//        //io流给ExcelReader
        ExcelReader excelReader=ExcelUtil.getReader(in);
//        //读取数据且转化为list
//        List<ProductPageBean> list = excelReader.readAll(ProductPageBean.class);
        //2.第二种导入方式
//        忽略第一行头(第一行是中文的情况),直接读取表的内容
        List<List<Object>> list = excelReader.read(1);
        List<ProductPageBean> productList = CollUtil.newArrayList();
        for (List<Object> row: list) {
            ProductPageBean product=new ProductPageBean();
            product.setProductName(row.get(0).toString());
            product.setProductSum(Long.valueOf(row.get(1).toString()));
            product.setPrice(Double.valueOf(row.get(2).toString()));
            product.setCost(Double.valueOf(row.get(3).toString()));
            product.setTypes(row.get(4).toString());
            product.setProductDesign(row.get(5).toString());
            product.setProductColor(row.get(6).toString());
            product.setProductDetail(row.get(7).toString());
            product.setProductMaterials(row.get(8).toString());
            product.setProductSize(row.get(9).toString());
            product.setSeason(row.get(10).toString());
            product.setImg(row.get(11).toString());
            product.setImg1(row.get(12).toString());
            product.setImg2(row.get(13).toString());
            productList.add(product);
//            ****类似一一对应****
        }
        //批量注册进数据库
        productService.saveAll(productList);
        flushRedis(Code.FILES_KEY);
        flushRedis(Code.SELECT_PRODUCT);
    }

    @GetMapping
    public Result selectList(){
        List<ProductPageBean> list = productService.ProductList();
        Integer code=list !=null ? Code.GET_OK:Code.GET_ERR;
        String msg=list!=null ? "查询到信息":"未查询到信息";
        return new Result(code,list,msg);
    }

    @GetMapping("/showId/{id}")
    public Result selectByShow(@PathVariable Integer id){
        List<ProductPageBean> list = productService.selectByShowId(id);
        Integer code=list !=null ? Code.GET_OK:Code.GET_ERR;
        String msg=list!=null ? "查询到信息":"未查询到信息";
        return new Result(code,list,msg);
    }

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    //删除缓存
    public void flushRedis(String key){
        String s = stringRedisTemplate.opsForValue().get(key);
        if (s!=null&&!"".equals(s)){
            stringRedisTemplate.delete(key);
        }
    }


}

